<?php

// +----------------------------------------------------------------------
// | Easyadmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\system;

use app\admin\model\SystemWebsite;
use app\admin\model\website\Lecturer as LecturerModel;
use app\admin\service\TriggerService;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;
use broadcast\redis\setRedis;
use app\admin\model\website\GiftGiving;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="站点管理")
 */
class LecturerList extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
        'rank'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new LecturerModel();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {

         //获取网站信息  start
         $website = setRedis::getCache(session("website"),'info');
         if (empty($website)) {
             $website = SystemWebsite::where("website_ident",session("website"))->find();
             if ($website) $website = $website->toArray();
             setRedis::setCache(session("website"),"info",$website,0);
         }
         if (isset($website['lecturer_arrange_pattern'])) {
             if ($website['lecturer_arrange_pattern'] == '2') {
                 return $this->redirect('thisimage');
             }
         }
 
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            
            if (session("admin.website") != '') {
                $where['website'] = session("admin.website");
            }
            
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->each(function ($item) {
                    $item['today'] = GiftGiving::where("lecturer",$item['lecturer'])->sum("total_price");
                });
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {


        if ($this->request->isAjax()) {
            $post = $this->request->post();
            

            if (session("admin.website") != '') {
                $post['website'] = session("admin.website");
            }
            try {
                $save = $this->model->save($post);
                $lecturer = LecturerModel::where("state",1)->order("rank desc")->select()->toArray();
                setRedis::setCache(session('website'),"LecturerList",$lecturer,0);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        $website = array();
        if (session("admin.website") == '') {
            $website = Db::name("system_website")->order("id desc")->field("website_ident as title")->select()->toArray();
        }
        $this->assign("website",$website);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $authIds = $this->request->post('auth_ids', []);
            $post['auth_ids'] = implode(',', array_keys($authIds));
            $rule = [];
            $this->validate($post, $rule);

            if (session("admin.website") != '') {
                $post['website'] = session("admin.website");
            }
            
            try {
                $save = $row->save($post);
                $lecturer = LecturerModel::where("state",1)->order("rank desc")->select()->toArray();
                setRedis::setCache(session('website'),"LecturerList",$lecturer,0);
                TriggerService::updateMenu($id);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row->auth_ids = explode(',', $row->auth_ids);

        $website = array();
        if (session("admin.website") == '') {
            $website = Db::name("system_website")->order("id desc")->field("website_ident as title")->select()->toArray();
        }

        $this->assign("website",$website);
        $this->assign('row', $row);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        
        try {
            $save = $row->delete();
            $lecturer = LecturerModel::where("state",1)->order("rank desc")->select()->toArray();
            if (empty($lecturer)) {
                setRedis::delCache(session('website'),"LecturerList");
            }else{
                setRedis::setCache(session('website'),"LecturerList",$lecturer,0);
            }
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $row = $this->model->find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    /**
     *  获取礼物贡献榜
     */
    public function record ()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();


            $count = GiftGiving::where($where)
            ->count();
            $list = GiftGiving::where($where)
            ->page($page, $limit)
            ->select();

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }


        return $this->fetch();
    }


    public function thisimage ()
    {   
        $website = SystemWebsite::where("website_ident",session("website"))->find();
        
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $website->lecturer_image = $post['lecturer_image'];
            $website->lecturer_image_moblie = $post['lecturer_image_moblie'];
            setRedis::setCache(session("website"),'info',$website->toArray(),0);
            $save = $website->save();
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign("image",$website['lecturer_image']);
        $this->assign("imageMoblie",$website['lecturer_image_moblie']);
        return $this->fetch();
    }

}
